import dayjs from "dayjs";
import {
  PlanGetPage, PlanSave, PlanDelete,
  PlanGetTemplatePlan, PlanImportTemplatePlan
} from "@/api/teacher/plan";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import qs from "qs";

export function usePlan() {
  const form = reactive({
    PlanId: 0,
    PlanName: "",
    CreateTime: "",
    ImportPlanId: "",
    Remarks: ""
  });

  const updatePlanDto = reactive({
    PlanId: "",
    PlanName: "",
    Type: '',
    isTemplate: 0,
    isTemplates: 0,
    CreateTime: "",
    ImportPlanId: "",
    isDisableEdit: false,
    Remarks: "",
    isEdit: 0
  });

  const dataList = ref([]);
  const loading = ref(true);
  const addDtoRef = ref();
  const addPanelVisible = ref(false);
  const updatePanelVisible = ref(false);
  const TemplateVisible = ref(false);
  const loadingTitle = ref(undefined);
  const templateList = ref();
  const isselectTemplate = ref();//判断是否有选中计划
  const selectTemplate = ref();// 选中的计划名称
  const rules = {
    PlanName: [
      {
        required: true,
        message: "请输入计划名称！",
        trigger: ["blur", "change"]
      }
    ],
    Type: [
      {
        required: true,
        message: "请输入计划类型！",
        trigger: ["blur", "change"]
      }
    ],
    isTemplate: [
      {
        required: true,
        message: "模板是否为空",
        trigger: ["blur", "change"]
      }
    ],
  };

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "计划名称",
      prop: "planName",
      minWidth: 200
    },
    {
      label: "任务类型",
      prop: "type",
      minWidth: 200,
      cellRenderer: ({ row }) => (
        <span>
          {
            row.type == 1 ? "实训模式" : "竞赛模式"
          }
        </span>
      )
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "来源模板",
      prop: "importPlanId",
      minWidth: 200
    },
    {
      label: "备注",
      prop: "remarks",
      minWidth: 300
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  function handleUpdate(row: any | undefined) {
    if (row) {

      loadingTitle.value = "修改计划";
      nextTick(() => {
        updatePlanDto.PlanId = row.planId;
        updatePlanDto.PlanName = row.planName;
        updatePlanDto.Remarks = row.remarks;
        updatePlanDto.Type = row.type
        updatePlanDto.isTemplate = row.isTemplate
        updatePlanDto.isTemplates = row.isTemplate
        updatePlanDto.isDisableEdit = row.isDisableEdit
        updatePlanDto.isEdit = row.isEdit
      });
    } else {
      updatePlanDto.PlanId = "";
      updatePlanDto.isTemplates = 0;
      updatePlanDto.isDisableEdit = false
      // updatePlanDto.isEdit =
      loadingTitle.value = "添加计划";

    }
    updatePanelVisible.value = true;
  }

  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await PlanDelete({ planId: row.planId });
      if (res.success) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch("");
      } else {
        ElMessage({
          message: res.msg,
          type: "error"
        });
      }
      // 确定
    }).catch(() => { })
  }

  function handleSizeChange(val: number) {
    onSearch("");
  }

  function handleCurrentChange(val: number) {
    onSearch("");
  }


  // 上传模板
  function HandTemplate() {
    if (!isselectTemplate.value) {
      ElMessage.warning("请选择计划");
      return
    }
    TemplateVisible.value = true;
  }

  // 保存上传模板
  async function HandleSvaTemplate() {
    const data = qs.stringify({
      templatePlanId: selectTemplate.value,
      importPlanId: isselectTemplate.value.planId
    })
    const res = await PlanImportTemplatePlan(data)
    if (res.success) {
      ElMessage.success(res.msg)
      closeTemplate()
      onSearch("");
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 关闭上传模板
  function closeTemplate() {
    TemplateVisible.value = false;
    isselectTemplate.value = ""
    selectTemplate.value = ""

  }

  // 搜索获取
  async function HandSearch(row) {
    const res = await PlanGetTemplatePlan(qs.stringify({ planId: row.planId }))
    isselectTemplate.value = row
    if (res.success) templateList.value = res?.data;
    else ElMessage.error(res.msg);
  }

  async function onSearch(PlanName: string) {
    loading.value = true;
    const { data } = await PlanGetPage({
      pageindex: pagination.currentPage,
      pagesize: pagination.pageSize,
      PlanName
    });

    dataList.value = data.items;
    pagination.total = data.totalCount;
    loading.value = false;
  }

  //添加计划
  const addPlan = (addDtoRef: FormInstance | undefined) => {
    (addDtoRef as any).validate(async valid => {
      if (!valid) return;
      const respone = await PlanSave(updatePlanDto);
      if (respone.status === 200) {
        ElMessage({
          message: respone.msg,
          type: "success"
        });
        ClosePanelVisible(addDtoRef);
        onSearch("");
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    });
  };

  async function updatePlan() {
    const respone = await PlanSave(updatePlanDto);
    if (respone.success) {
      onSearch("");
      updatePanelVisible.value = false;
      ElMessage({
        message: "修改成功",
        type: "success"
      });
    }
  }

  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    updatePanelVisible.value = false;
    row.resetFields();
  }

  // const resetForm = () => {
  //   form.PlanName = "";
  //   onSearch("");
  // };

  onMounted(() => {
    onSearch("");
  });

  return {
    form,
    loading,
    columns,
    dataList,
    addDtoRef,
    pagination,
    templateList,
    loadingTitle,
    selectTemplate,
    TemplateVisible,
    addPanelVisible,
    updatePlanDto,
    updatePanelVisible,
    rules,
    onSearch,
    HandSearch,
    // resetForm,
    handleUpdate,
    handleDelete,
    HandTemplate,
    closeTemplate,
    HandleSvaTemplate,
    handleSizeChange,
    ClosePanelVisible,
    handleCurrentChange,
    addPlan,
    updatePlan
  };
}
